import { Component,ViewChild,ElementRef } from "@angular/core"
import { NavController,AlertController,LoadingController,NavParams } from "ionic-angular"
import { HttpClient,HttpHeaders } from '@angular/common/http';
import { NativeStorage } from '@ionic-native/native-storage';
import { TranslateService } from '@ngx-translate/core';

import { PostfeePage } from '../../../pay/postfee/postfee';
import { AppConfig } from '../../../../app/app.config';
import { PostlistPage } from '../../../more/postlist/postlist'
declare var google;
@Component({
    selector: "page-filter",
    templateUrl: "service.html",
})

export class PostservicePage{
    @ViewChild('map') mapElement:ElementRef;
    alert_sign=false;
    marker:any;
    map:any;
    addresslist=[];
    info = {
        cate:'Photo|service',
        address: '',
        price: '',
        price_unit:'1',
        price_type:'',
        service_start:'',
        service_end: '',
        owner_name:'',
        owner_email: '',
        owner_tel: '',
        autoorder: 1,
        share: 0,
        description: '',
        top_status: '',
        top_starttime: '',
        top_endtime: '',
        is_share_info:'',
        latitude:'',
        longitude:'',
        place_id:'',
    }
    id:string
    loading:any
    token:string
    pre_price:string
    advertising:string
    dependentColumns:any;
    constructor(
        private http:HttpClient,
        private alertCtrl:AlertController,
        private navCtrl:NavController,
        private loadingCtrl:LoadingController,
        private stroge:NativeStorage,
        private navParams:NavParams,
        private translate: TranslateService,
    ){
        this.dependentColumns = [
            {
              options: [
                { text: 'Photo service', value: 'Photo|service' },
                { text: 'Survey Service', value: 'Survey|Service' },
                { text: 'Insurance', value: 'Insurance' },
                { text: 'Lawyer', value: 'Lawyer' },
                { text: 'Clean', value: 'Clean' },
                { text: 'Move house', value: 'Move|house' },
                { text: 'Decoration', value: 'Decoration' },
                { text: 'Water heater', value: 'Water|heater' },
                { text: 'Water leakage', value: 'Water|leakage' },
                { text: 'Loan agency', value: 'Loan|agency' },
              ]
            }
          ];
        this.advertising = './assets/imgs/banner.png'
        translate.setDefaultLang('en');
    }
    ionViewDidEnter(){
      this.stroge.getItem('lang').then(res=>{
          this.translate.use(res)
      })
    }
    ionViewDidLoad(){
        this.id = this.navParams.get('id');
        this.stroge.getItem('token').then(token=>{
            this.token = token
            if(this.id){
                this.http.get(AppConfig.getUrl()+'service/info?id='+this.id+'&token='+token).subscribe(res=>{
                    if(res['code']==101){
                        this.info = res['data']
                    }
                })
            }
            this.http.get(AppConfig.getUrl()+'index/setting?token='+token).subscribe((res)=>{
                if(res['code']==101){
                    this.pre_price = res['data']['info_service']
                }
            })
            this.http.get(AppConfig.getUrl()+'user/getInfo?token='+token).subscribe((res)=>{
                if(res['code']==101){
                    this.info.owner_name = res['data']['lastname']
                    this.info.owner_email = res['data']['email']
                    this.info.owner_tel = res['data']['mobile']
                }
            })
        })
        this.stroge.getItem('latlng').then(latlng=>{
            this.loadmap(latlng);
        }).catch(()=>{
            this.loadmap({lat:43.0741904,lng:-88.2801122});
        })
        this.http.get(AppConfig.getUrl()+'Links/index').subscribe((res)=>{
            if(res['code']==101){
                this.advertising = AppConfig.getMainUrl() + res['data'][4]['logo']
            } 
        })
        
    }
    loadmap(latlng){
        this.map = new google.maps.Map(this.mapElement.nativeElement,{
            center:{
                lat:latlng[0]?latlng[0]:43.0741904,
                lng:latlng[0]?latlng[1]:-88.2801122,
            },
            zoom:8,
            disableDefaultUI: true,
        })
        
        this.map.addListener('click',(e)=>{
            if(this.marker){
                this.marker.setPosition(e.latLng)
            }else{
                this.marker = new google.maps.Marker({
                    position: e.latLng,
                    map: this.map
                });
            }
            this.http.get('https://maps.google.cn/maps/api/geocode/json?latlng='+e.latLng.lat()+','+e.latLng.lng()+'&language=EN&key=AIzaSyD-3zV0yAE9iwRXvPm7E-2pgrjYFaVZqrA').subscribe(jsonArray=>{
                if(jsonArray['results'].length>0){
                    for(let i=0;i<jsonArray['results'].length;i++){
                        if(jsonArray['results'][i]['types'][0]=='locality'){
                            this.info.place_id = jsonArray['results'][i].place_id;
                        }
                    }
                }
                this.http.get('https://maps.googleapis.com/maps/api/place/nearbysearch/json?location='+e.latLng.lat()+','+e.latLng.lng()+'&radius=500&key=AIzaSyD-3zV0yAE9iwRXvPm7E-2pgrjYFaVZqrA').subscribe(res=>{
                    this.addresslist = res['results'];
                })
            })
            
        })
    }
    alertb(title,subTitle){
        let alert = this.alertCtrl.create({
            title: title,
            subTitle: subTitle,
            buttons: ['OK']
        });
        alert.present();
    }
    loadWait(){
        this.loading = this.loadingCtrl.create({
            content: 'Please wait...'
        });
        this.loading.present();
    }
    submit(){
        if( !(this.info.address&&this.info.latitude&&this.info.longitude) ){
            this.alertb('Error','Please select an address!');
            return false;
        }
        if( !this.info.price ){
            this.alertb('Error','Please fill in the price!');
            return false;
        }
        if( !this.info.owner_name ){
            this.alertb('Error','Please fill in the name!');
            return false;
        }
        if( !this.info.owner_email ){
            this.alertb('Error','Please fill in the email!');
            return false;
        }
        if( !this.info.owner_tel ){
            this.alertb('Error','Please fill in the mobile number!');
            return false;
        }
        this.loadWait();
        this.stroge.getItem('token').then((res)=>{
            if(!this.id){
                this.http.post(AppConfig.getUrl()+'service/add?token='+res, AppConfig.urlEcode(this.info), { headers: new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded' }) }).subscribe( res => {
                    if(res['code']===101){
                        this.alertb('successed!','');
                        this.navCtrl.pop()
                        this.navCtrl.push(PostlistPage)
                    }else{
                        this.alertb('Error!',res['msg']);
                    }
                    this.loading.dismiss()
                })
            }else{
                this.http.post(AppConfig.getUrl()+'service/edit?token='+res, AppConfig.urlEcode(this.info), { headers: new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded' }) }).subscribe( res => {
                    if(res['code']===101){
                        this.alertb('Edit successed!','');
                        this.navCtrl.pop()
                    }else if(res['code']==203){
                        this.navCtrl.push(PostfeePage,{data:res['data']})
                    }else{
                        this.alertb('Error!',res['msg']);
                    }
                    this.loading.dismiss()
                })
            }
        })
        
    }
}